package com.yifeng.repo.controller.statemachine.web;

import com.gomcarter.frameworks.base.context.SpringContextHolder;
import com.gomcarter.frameworks.base.json.ErrorCode;
import com.yifeng.repo.base.utils.servlet.RequestHelper;
import com.yifeng.repo.base.utils.servlet.ResponseHelper;
import com.yifeng.repo.controller.statemachine.fsm.audit.AuditStatemachine;
import com.yifeng.repo.controller.statemachine.fsm.audit.biz.AuditContext;
import com.yifeng.repo.controller.statemachine.fsm.audit.biz.AuditEventEnum;
import com.yifeng.repo.controller.statemachine.fsm.audit.biz.AuditStateEnum;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by daibing on 2024/9/21.
 */
@Slf4j
public class StatemachineServlet  extends HttpServlet {
    public static final String AUDIT_DO_AUDIT = "/audit/doAudit";
    public static final String AUDIT_GET_UML = "/audit/getUml";
    private final String apiPrefix;

    public StatemachineServlet(String apiPrefix) {
        this.apiPrefix = apiPrefix;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int index = uri.indexOf(apiPrefix + "/") + apiPrefix.length() + 1;
        try {
            if (uri.endsWith(AUDIT_DO_AUDIT)) {
                AuditContext context = new AuditContext();
                context.setScene(req.getParameter("scene"));
                context.setId(Long.parseLong(req.getParameter("id")));
                context.setSourceState(AuditStateEnum.resolve(req.getParameter("sourceState")));
                context.setEvent(AuditEventEnum.resolve(Integer.parseInt(req.getParameter("auditEvent"))));
                AuditStateEnum target = SpringContextHolder.getBean(AuditStatemachine.class).doAudit(context);
                ResponseHelper.doWrite(resp, target);
            } else if (uri.endsWith(AUDIT_GET_UML)) {
                String uml = SpringContextHolder.getBean(AuditStatemachine.class).getUml();
                ResponseHelper.doWrite(resp, uml);
            } else {
                ResponseHelper.doError(resp, ErrorCode.noPermission.getCode(),
                        "http.method_post_not_supported from " + RequestHelper.getRemoteAddress(req));
            }
        } catch (Throwable t) {
            log.error("statemachine doPost error: ", t);
            ResponseHelper.doError(resp, ErrorCode.systemInternalError.getCode(), t.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}
